<template>
  <div class="detail-container">
    <div class="back-header">
      <div class="back-btn" @click="router.back()">←</div>
      <h1>商品详情</h1>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else class="product-detail">
      <div class="product-image">
        <img v-if="product.image" :src="`http://localhost:3005/${product.image}`" :alt="product.title">
      </div>
      <div class="product-info">
        <h2>{{ product.title }}</h2>
        <div class="tags">
          <span class="tag">人气王</span>
          <span class="tag">冷热可选</span>
        </div>
        <p class="description">{{ product.content }}</p>
        <div class="price-section">
          <span class="price">¥{{ product.price }}</span>
          <button class="add-to-cart" @click="addToCart(product)">加入购物车</button>
        </div>
      </div>
      <!-- 评论区域 -->
      <div class="comments-section">
        <h3>商品评价</h3>
        <div v-if="commentsLoading" class="loading">加载评论中...</div>
        <div v-else-if="comments.length === 0" class="no-comments">暂无评价</div>
        <div v-else class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment-item">
            <div class="comment-header">
              <span class="user-name">{{ comment.username || '匿名用户' }}</span>
              <div class="rating">
                <span v-for="n in 5" :key="n" 
                      :class="['star', n <= comment.rating ? 'filled' : '']">★</span>
              </div>
            </div>
            <p class="comment-content">{{ comment.content }}</p>
            <span class="comment-time">{{ comment.createTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCartStore } from '../../stores/cart'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()

interface Product {
  id: number
  title: string
  content: string
  price: number
  image?: string
}

interface Comment {
  id: number
  userId: string
  content: string
  rating: number
  createTime: string
  userName?: string
}

const product = ref<Product>({
  id: 0,
  title: '',
  content: '',
  price: 0
})
const comments = ref<Comment[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const commentsLoading = ref(false)

const fetchProductDetail = async () => {
  if (!route.params.id) {
    error.value = '商品ID不能为空'
    loading.value = false
    return
  }

  try {
    const response = await fetch('http://localhost:3005/cart/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: Number(route.params.id) })
    })
    
    if (!response.ok) {
      throw new Error(`获取商品详情失败: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    console.log('商品详情数据:', data) // 添加日志输出
    
    if (data.success === '成功' && Array.isArray(data.result)) {
      const detail = data.result.find(item => item.id === Number(route.params.id))
      if (detail) {
        product.value = {
          id: detail.id,
          title: detail.title || '未知商品',
          content: detail.content || '暂无描述',
          price: Number(detail.price) || 0,
          image: detail.image
        }
      } else {
        throw new Error('未找到商品详情')
      }
    } else {
      throw new Error(data.msg || '获取商品详情失败')
    }
  } catch (err) {
    console.error('获取商品详情错误:', err)
    error.value = err instanceof Error ? err.message : '获取商品详情失败'
  } finally {
    loading.value = false
  }
}

const fetchComments = async () => {
  commentsLoading.value = true
  try {
    const response = await fetch('http://localhost:3005/appraise', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ productId: route.params.id })
    })

    if (!response.ok) {
      throw new Error('获取评论失败')
    }

    const data = await response.json()
    if (data.success === '成功' && Array.isArray(data.result)) {
      comments.value = data.result
    }
  } catch (err) {
    console.error('获取评论错误:', err)
  } finally {
    commentsLoading.value = false
  }
}

const addToCart = (item: Product) => {
  cartStore.addToCart(item)
}

onMounted(() => {
  fetchProductDetail()
  fetchComments()
})
</script>

<style scoped>
.detail-container {
  padding-bottom: 64px;
  background: #f7f7f7;
  min-height: 100vh;
}

.back-header {
  background: #fff;
  padding: 16px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  font-size: 24px;
  color: #333;
  cursor: pointer;
  padding: 4px 12px;
}

.back-header h1 {
  margin: 0;
  font-size: 18px;
  flex: 1;
  text-align: center;
}

.product-detail {
  background: #fff;
  margin: 16px;
  border-radius: 12px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  aspect-ratio: 4/3;
  background: #f8f8f8;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image img {
  width: 400px;
  height: 100%;
  object-fit: contain;
  object-position: center;
}

.product-info {
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  margin-top: -20px;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.product-info h2 {
  margin: 0 0 16px;
  font-size: 28px;
  color: #333;
  font-weight: 600;
}

.tags {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  padding: 6px 14px;
  background: #fff2f2;
  color: #e4393c;
  border: 1px solid #ffdbdb;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
}

.description {
  font-size: 16px;
  color: #666;
  line-height: 1.8;
  margin-bottom: 24px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 8px;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-top: 1px solid #eee;
}

.price {
  font-size: 32px;
  color: #e4393c;
  font-weight: bold;
}

.add-to-cart {
  background: linear-gradient(135deg, #ff4d4d 0%, #e4393c 100%);
  color: #fff;
  border: none;
  padding: 14px 32px;
  border-radius: 28px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(228, 57, 60, 0.2);
}

.add-to-cart:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(228, 57, 60, 0.3);
}

.comments-section {
  margin-top: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.comments-section h3 {
  margin: 0 0 24px;
  font-size: 20px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.comments-section h3::before {
  content: "";
  width: 4px;
  height: 20px;
  background: #e4393c;
  margin-right: 8px;
  border-radius: 2px;
}

.comment-item {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-name {
  font-size: 15px;
  color: #333;
  font-weight: 500;
}

.rating {
  display: flex;
  gap: 3px;
}

.star {
  color: #ddd;
  font-size: 16px;
}

.star.filled {
  color: #f7ba2a;
}

.comment-content {
  font-size: 15px;
  color: #666;
  line-height: 1.6;
  margin: 12px 0;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.comment-time {
  font-size: 13px;
  color: #999;
}
</style>